import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: YKH
 * Date: 2022-10-25
 * Time: 15:28
 */
class Student {

    public int studentid;
    public int classid;
}

//获取 http中的 quarystring
@WebServlet("/studentinfo")
public class StudentInfoServlet extends HelloServlet{
    //处理get请求
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html setchar=utf8");
        //获取QuaryString 此处获取到的是为字符串
        String queryString = req.getQueryString();
        System.out.println(queryString);

        //要想获取到值就需要通过req.getParamter()方法 :
        //此方法的效果是 拿到query String中的键值对, 根据key来获取对应的value
        String classid = req.getParameter("classid");  //通过key获取到对应的value值
        String studentid = req.getParameter("studentid");

        resp.getWriter().write("classid: " + classid +"   "+ "studentid:  "+ studentid );
    }

    //处理post请求
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html setchar=utf8");
        /*//获取到 body 中的参数
        //约定body使用 application/x-www-form-urlencoded 这种格式
        //这个格式就形如 classid=104&studentid=20
        //这个格式和 querystring相同, 只是数据在 body中
        //针对这种格式, 获取到值的方法仍然是getParameter

        String classid = req.getParameter("classid");  //通过key获取到对应的value值
        String studentid = req.getParameter("studentid");
        System.out.println("classid: " + classid +"   "+ "studentid:  "+ studentid);
        resp.getWriter().write("classId: " + classid +"   "+ "studentId:  "+ studentid );
*/
        //处理josn格式的参数 先导入 jackjosn的依赖 -> 创建ObjectMapper对象,使用其中的readVaule方法, 其中两个参数 1是 请求的body, 和构造的类的反射
        //最后会返回对应类的对象
        ObjectMapper objectMapper = new ObjectMapper();
        Student student = objectMapper.readValue( req.getInputStream(),Student.class);
        System.out.println("classid: " + student.classid +"   "+ "studentid:  "+ student.studentid);
        resp.getWriter().write("classid: " + student.classid +"   "+ "studentid:  "+ student.studentid);

    }
}

